package com.lagou.utils;


import com.alibaba.druid.pool.DruidDataSource;
import com.lagou.anno.Autowired;
import com.lagou.anno.Component;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 将连接对象绑定到当前线程。
 * 规则：首先去map中获取，如果有则直接返回，没有则去创建新的连接。
 *
 */
@Component
@PropertySource({"classpath:jdbc.propertites"})
public class ConnectionUtils {

    private  ThreadLocal<Connection> connections=new ThreadLocal<>();

    public  Connection getConnection() throws SQLException {
        Connection connection = connections.get();
        if (connection==null){
            DruidDataSource dataSource=new DruidDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/bank");
            dataSource.setUsername("root");
            dataSource.setPassword("123456");
            connection = dataSource.getConnection();
            connections.set(connection);
        }
        return connection;
    }
}
